<?php

namespace app\common\model;

use think\Model;

class Base extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 列表
     * @param array $map
     * @param int $page
     * @param int $limit
     * @param string $order
     * @param bool|true $field
     * @return mixed
     */
    public function getList($map = [], $page = 0, $limit = 10, $order = "create_time desc", $field = true, $append = [])
    {
        $cache = true;
        if (isset($map['cache']) && !$map['cache']) {
            $cache = false;
            unset($map['cache']);
        }
        $key = md5(json_encode($map) . $page . $limit . $order . $field . request()->baseFile() . request()->controller() . request()->action() . request()->module());
        $ret = cache($key);
        if ($ret && strstr(request()->baseFile(), 'api.php') && $cache) {
            return $ret;
        }
        $obj = $this->where($map)->field($field)->orderRaw($order);
        $ret = [];
        $ret['count'] = (int)$obj->count();
        $ret['page'] = (int)$page;
        $ret['limit'] = (int)$limit;
        if ($page) {
            $obj = $obj->page($page)->limit($limit);
        }
        if (!empty($append)) {
            $obj = $obj->append($append)->select();
        } else {
            $obj = $obj->select();
        }
        if (!$obj) return [];
        $ret['list'] = $obj->toArray();
        cache($key, $ret, 600);
        return $ret;
    }

    /**
     * 获取列表数据
     * @param array $condition
     * @param bool $field
     * @param string $order
     * @param string $alias
     * @param array $join
     * @param string $group
     * @param null $limit
     * @return array
     */
    final public function pageList($condition = [], $field = true, $order = '', $page = 1, $page_size = 15,$append=[],$hidden=[], $alias = 'a', $join = [], $group = null)
    {
        $_obj = $this->field($field)->alias($alias)->where($condition)->order($order);
        if (!empty($join)) {
            $_obj = $this->parseJoin($_obj, $join);
        }
        if (!empty($group)) {
            $_obj = $_obj->group($group);
        }
        $count = $_obj->count();
        if ($page_size == 0) {
            //查询全部
            $result_data = $_obj->append($append)->select();
        } else {
            $result_data = $_obj->page($page, $page_size)->append($append)->hidden($hidden)->select();
        }
        $result['count'] = $count;
        $result['list'] = $result_data;
        return $result;
    }
}
